package com.heima.search.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.heima.common.constants.SearchContants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.vos.SearchArticleVo;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.SearchHistoryService;
import com.heima.utils.thread.ThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SearchHistoryServiceImpl implements SearchHistoryService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存历史记录
     * @param userId
     * @param keyWords
     */
    @Async
    public void insert(Integer userId, String keyWords) {
        //校验参数
        if (userId == null || StringUtils.isEmpty(keyWords)) {
            return;
        }

        //查询有没有
        Query queryOne = new Query(Criteria.where("userId").is(userId).and("keyword").is(keyWords));
        ApUserSearch apUserSearchFind = mongoTemplate.findOne(queryOne, ApUserSearch.class);

        if (apUserSearchFind != null) {
            apUserSearchFind.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearchFind);
            return;
        }

        ApUserSearch apUserSearch = ApUserSearch.builder()
                .createdTime(new Date())
                .userId(userId)
                //雪花算法生成id
                .id(IdWorker.getId())
                .keyword(keyWords)
                .build();
        Query queryList = new Query(Criteria.where("userId").is(userId));
        queryList.with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> apUserSearches = mongoTemplate.find(queryList, ApUserSearch.class);
        if (apUserSearches == null || apUserSearches.size() < SearchContants.SEARCH_HISTORY_MAX_QUANTITY) {
            mongoTemplate.save(apUserSearch);
            return;
        }
        ApUserSearch apUserSearchLast = apUserSearches.get(apUserSearches.size() - 1);
        mongoTemplate.remove(Query.query(Criteria.where("id").is(apUserSearchLast.getId())), ApUserSearch.class);
        mongoTemplate.save(apUserSearch);
    }

    /**
     * 历史记录列表显示
     * @return
     */
    @Override
    public ResponseResult loadHistory() {
        List<ApUserSearch> apUserSearchList = mongoTemplate.find(Query.query(Criteria.where("userId").is(ThreadLocalUtil.get())), ApUserSearch.class);
        return ResponseResult.okResult(apUserSearchList);
    }

    /**
     * 删除历史记录
     * @param historySearchDto
     * @return
     */
    @Override
    public ResponseResult delHistory(HistorySearchDto historySearchDto) {
        if (historySearchDto != null && historySearchDto.getId() != null) {
            mongoTemplate.remove(Query.query(Criteria.where("_id").is(historySearchDto.getId())), ApUserSearch.class);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }
}
